﻿using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace CopyFile
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            IniFile.SaveFormSet(this, comboBox1);

        }
        List<string> fileList = new List<string>();
        private void btnReadFileList_Click(object sender, EventArgs e)
        {
            string baseDir = txBaseDir.Text;

            if (Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory) == Path.GetPathRoot(baseDir))
            {
                string[] sarr1 = baseDir.Split('\\');
                string[] sarr2 = AppDomain.CurrentDomain.BaseDirectory.Split('\\');
                string newDir = "";
                int DirLen1 = 0;
                int remainDirLen2 = sarr2.Length;
                for (int i = 0; i < sarr1.Length && i < sarr2.Length; i++)
                {
                    if (sarr1[i] == sarr2[i])
                    {
                        DirLen1++;
                        remainDirLen2--;
                    }
                }
                for (int i = 1; i < remainDirLen2; i++)
                {
                    newDir += "..\\";
                }
                for (int i = DirLen1; i < sarr1.Length; i++)
                {
                    newDir += sarr1[i] + "\\";
                }
                txBaseDir.Text = newDir.Trim('\\');
            }

            if (!Directory.Exists(baseDir))
            {
                MessageBox.Show("目标目录不存！");
                return;
            }
            fileList = new List<string>();
            GetFiles(baseDir);
            int trimLen = baseDir.Trim('\\').Length + 1;
            List<string> addList = new List<string>();
            foreach (string s in fileList)
            {
                bool canAdd = true;
                string filename = s.Substring(trimLen);
                if (ckContianKey.Checked)
                {
                    canAdd = false;
                    foreach (string containKey in txContainKey.Lines)
                    {
                        string ss = containKey.Trim();
                        if (string.IsNullOrEmpty(ss)) continue;
                        if (filename.Contains(ss))
                        {
                            canAdd = true;
                            break;
                        }
                    }
                }
                if (ckExcludeKey.Checked)
                {
                    foreach (string exludeKey in txExcludeKey.Lines)
                    {
                        string ss = exludeKey.Trim();
                        if (string.IsNullOrEmpty(ss)) continue;
                        if (filename.Contains(ss))
                        {
                            canAdd = false;
                            break;
                        }
                    }
                }

                if (canAdd)
                {
                    FileInfo f = new FileInfo(Path.Combine(baseDir, filename));
                    if (f.LastWriteTime > dpStartTime.Value)
                    {
                        addList.Add(f.FullName);
                    }
                }
            }
            txFileList.Lines = addList.ToArray();
        }
        private void GetFiles(string dir)
        {
            fileList.AddRange(Directory.GetFiles(dir));
            string[] dirs = Directory.GetDirectories(dir);
            foreach (string s in dirs)
            {
                GetFiles(s);
            }
        }

        private void btnGenerateZip_Click(object sender, EventArgs e)
        {
            if (txFileList.Lines.Length == 0)
            {
                MessageBox.Show("没有要压缩的文件");
                return;
            }
            if (txOutDir.Text == "") txOutDir.Text = ".\\";

            if (Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory) == Path.GetPathRoot(txOutDir.Text))
            {
                string[] sarr1 = txOutDir.Text.Split('\\');
                string[] sarr2 = AppDomain.CurrentDomain.BaseDirectory.Split('\\');
                string newDir = "";
                int DirLen1 = 0;
                int remainDirLen2 = sarr2.Length;
                for (int i = 0; i < sarr1.Length && i < sarr2.Length; i++)
                {
                    if (sarr1[i] == sarr2[i])
                    {
                        DirLen1++;
                        remainDirLen2--;
                    }
                }
                for (int i = 1; i < remainDirLen2; i++)
                {
                    newDir += "..\\";
                }
                for (int i = DirLen1; i < sarr1.Length; i++)
                {
                    newDir += sarr1[i] + "\\";
                }
                txOutDir.Text = newDir.Trim('\\');
            }
            if (txOutDir.Text == "") txOutDir.Text = ".\\";
            if (string.IsNullOrEmpty(txZipName.Text))
            {
                txZipName.Text = "{0:yyyyMMddHHmmss}";
            }

            string ZipedFile = Path.Combine(txOutDir.Text, string.Format(txZipName.Text, DateTime.Now) + ".zip");
            if (!Directory.Exists(Path.GetDirectoryName(ZipedFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(ZipedFile));
            }
            if (File.Exists(ZipedFile)) File.Delete(ZipedFile);
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            try
            {
                s.SetLevel(6);
                //s.Password = "";
                HashSet<string> dirs = new HashSet<string>();
                int trimLen = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, txBaseDir.Text)).FullName.Trim('\\').Length + 1;
                ZipEntry entry = null;
                FileStream fs = null;
                Crc32 crc = new Crc32();
                foreach (string filename in txFileList.Lines)
                {
                    //string filedir = Path.GetDirectoryName(filename.Substring(trimLen));
                    //if (false && !dirs.Contains(filedir) && !string.IsNullOrEmpty(filedir))
                    //{
                    //    entry = new ZipEntry(Path.GetFileName(filedir) + "/");  //加上 “/” 才会当成是文件夹创建
                    //    s.PutNextEntry(entry);
                    //    s.Flush();
                    //    dirs.Add(filedir);
                    //}
                    fs = File.OpenRead(filename);
                    FileInfo f = new FileInfo(filename);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry(filename.Substring(trimLen));
                    entry.DateTime = f.LastWriteTime;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
                MessageBox.Show("生成更新包" + ZipedFile);
                OpenFolderSel.OpenFileAndSel(AppDomain.CurrentDomain.BaseDirectory + ZipedFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                s.Finish();
                s.Close();
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            txFileList.Text = "";
        }

        private void txBaseDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            FileInfo f = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + txBaseDir.Text);
            path.SelectedPath = f.FullName;
            if (path.ShowDialog() == DialogResult.OK)
            {
                txBaseDir.Text = path.SelectedPath;
            }

        }

        private void btnSaveSet_Click(object sender, EventArgs e)
        {
            IniFile.SaveSet(this, comboBox1.Text);
            IniFile.LoadCase(comboBox1);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            IniFile.LoadSet(this, comboBox1.Text);
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            IniFile.DelSet(this, comboBox1.Text);
            IniFile.LoadCase(comboBox1);
        }
    }
}
